#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFile>
#include <QDebug>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect( &timer, SIGNAL(timeout()), this, SLOT(getStatus()) );
    connect( &crq, SIGNAL(signal_message(QString)), this, SLOT(message(QString)) );
    connect( &crq, SIGNAL(signal_found_obj(short)), this, SLOT(record( short )) );
   // connect( &crq, SIGNAL(signal_not_found()), this, SLOT(record( short )) );


    memset( point, 0 ,sizeof( short )*100 );
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::message( QString msg ){
    ui->textEdit->append( msg );
}

void MainWindow::getStatus(){

}

//03 r
//06 w
//10 ws
void MainWindow::on_checkBox_toggled(bool checked)
{
    qDebug()<< checked;
    if(checked){
        crq.connectRobotiq();
    }else{
        crq.disconnectRobotiq();
    }
}
void MainWindow::readyReadSlot()
{
//    QByteArray arr = m_reader.readAll();
//    qDebug()<<"get: " << arr;
}

void MainWindow::on_pushButton_read_clicked()
{
    ui->textEdit->append(  "============"  );
    for(int i=0;i<5;i++){
        ui->textEdit->append(   QString::number(  crq.r_reg[ i ] , 16 )  );
    }
     ui->label->setText(  QString::number(  crq.r_reg[ 0 ] , 16 ) );
    ui->label_2->setText(  QString::number(  crq.r_reg[ 1 ] , 16 ) );
    ui->label_3->setText(  QString::number(  crq.r_reg[ 2 ] , 16 ) );
    ui->label_4->setText(  QString::number(  crq.r_reg[ 3 ] , 16 ) );
    ui->label_5->setText(  QString::number(  crq.r_reg[ 4 ]  , 16 ) );
}

void MainWindow::on_pushButton_write_clicked()
{

}

void MainWindow::on_pushButton_open_clicked()
{
     crq.move( 0x0 , 0xff , 0xff );
}

void MainWindow::on_pushButton_close_clicked()
{
     crq.move( ui->spinBox_pos->value() , 0xff , 0xff );
}

void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    ui->lineEdit->setText( arg1 );
}

void MainWindow::on_pushButton_active_clicked()
{
     crq.acitved();
}

#include <QThread>
void MainWindow::on_pushButton_test_clicked()
{
    crq.move( 0 , 0xff , 0xff );
    QThread::usleep(1000000);
     crq.move( ui->spinBox_point_2->value() , 0xff , 0xff );
}

void MainWindow::on_pushButton_record_clicked()
{
    int pos=(   (crq.r_reg[ 2 ] &0xFF00)>>8  );
  point[ ui->spinBox_point->value() ] = pos ;// ((crq.r_reg[ 2 ] &0xFF00)>>8);
   qDebug()<< "1 record"<< point[ ui->spinBox_point->value() ];

   on_pushButton_read_clicked();
}

void MainWindow::on_pushButton_pickup_clicked()
{
    crq.checkObj();
}

void MainWindow::on_pushButton_stop_clicked()
{
    crq.stop();
}


void MainWindow::move_to_point(int index){
       crq.move( point[index] , 0xff , 0xff );
}
void MainWindow::record(short  pos){
    ui->spinBox_point_2->setValue(  pos );
   qDebug()<< "2 record"<< pos;

   on_pushButton_read_clicked();
}

void MainWindow::on_spinBox_pos_valueChanged(int arg1)
{
    crq.move( arg1, 0x60 , 0x60 );
}
